package com.yuan.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuan.ayuancity.entity.Admins;
import com.yuan.ayuancity.entity.Users;
import com.yuan.ayuancity.mapper.AdminsMapper;
import com.yuan.ayuancity.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *   Security身份验证:判断输入的用户是否存在
 * </p>
 *
 * @author asuyuan
 * @since 2023/3/3
 */
@Component
public class UserDetailsServiceimpl implements UserDetailsService {

    //可以用@Autowired注入
    AdminsMapper adminsMapper;
  //别忘在mapper成添加@Mapper

  public UserDetailsServiceimpl(AdminsMapper adminsMapper){
        this.adminsMapper=adminsMapper;
    }

    /**
     * username前端传回来的名字，名字必须是username
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Admins> queryWrapper=new QueryWrapper<>();
        // queryWrapper.select("admin_id","admin_name","admin_account","admin_sex","admin_img","admin_phone","admin_lastip","create_time");
        queryWrapper.eq("admin_account", username);
        Admins admins = adminsMapper.selectOne(queryWrapper);
        if (admins==null){
          throw new  UsernameNotFoundException("用户名不存在");
        }
        // admins.setAdminPassword("{noop}"+admins.getAdminPassword());
        return new SecurityUser(admins);
    }

    public static void main(String[] args) {
            String bcrypt = BCrypt.hashpw("admin", BCrypt.gensalt());
            System.out.println("bcrypt = " + bcrypt);

            boolean matches = BCrypt.checkpw("123456", "$2a$10$zCfvWZRa3otRLjieImPtBuLIVdTdhTOrZS4DUSIsHDXtIpAK9stdm");
            System.out.println("matches = " + matches);
    }
}

